package presentation;

import java.awt.Color;
import java.awt.Dimension;
import java.io.*;
import java.util.Arrays;


import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.border.BevelBorder;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;

import control.CControl;

public class PMotorErrorPanel extends JPanel implements Observer {
	
	HashMap<Integer, String> errmap;
	JTextPane t;
	int last_err;
	
	public PMotorErrorPanel(CControl cControl) throws FileNotFoundException
	{
		System.out.print(cControl.getRootPath() + "err.txt");
		BufferedReader CSVFile = new BufferedReader(new FileReader(cControl.getRootPath() + "err.txt"));
		last_err = 0;
		t = new JTextPane();
		SimpleAttributeSet s = new SimpleAttributeSet();
		StyleConstants.setAlignment(s, StyleConstants.ALIGN_LEFT);
		t.setParagraphAttributes(s, true);
		t.setText("Motor Messages:\n");
		
		this.setBackground(Color.white);
		this.setBorder(new BevelBorder(BevelBorder.LOWERED));
		
		
		
		this.setMinimumSize(new Dimension(400,200));
		errmap = new HashMap<Integer, String>();
		try
		{
		String dataRow = CSVFile.readLine(); // Read first line.
		  // The while checks to see if the data is null. If 
		  // it is, we've hit the end of the file. If not, 
		  // process the data.

		  while (dataRow != null){
		   String[] dataArray = dataRow.split(",");
		   int i = 0;
		   Integer id = 0;
		   String message = "";
		   for (String item:dataArray) {
			  if(i == 4)
			  {
				  System.out.println("errcode: " + item + "\t");
				  id = Integer.parseInt(item.substring(2),16);
			  }
			  else if(i == 7)
			  {
				  System.out.println("errtextshort: " + item + "\t");
				  message = item;
			  }
			  else if(i == 8)
			  {
				  System.out.println("errtext long: " + item + "\t");
				  message += "\t description: " +  item;
			  }
			  else if (i == 9)
			  {
				  System.out.println("required action: " + item + "\t");
				  message += "\t action: " +  item;
			  }
		      i++;
		   }
		   
		   errmap.put(id, message);
		   
		   System.out.println(); // Print the data line.
		   dataRow = CSVFile.readLine(); // Read next line of data.
		  }
		  // Close the file once all data has been read.
		  CSVFile.close();
		}
		catch(IOException e)
		{
			
		}
		
		
		this.add(t);
		 
		cControl.addRegisterObserver("MBN_MC_EmMsgFaultID", this);
		  
		
	}
	@Override
	public void update(Observable arg0, Object arg1) {
		// TODO Auto-generated method stub
		
		int val = ((Long)arg1).intValue();
		if(val != last_err)
		{
			t.setText(t.getText() + errmap.get(val) + "\n");
			last_err = val;
		}

	}

}
